package com.shawn.springboot.integeration.netty.server;

import com.shawn.springboot.integeration.netty.server.initializer.MyServerInitializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import lombok.extern.slf4j.Slf4j;

/**
 * @author zhangjian
 * @title: NettyServer
 * @projectName 12-springboot学习
 * @description: 服务端
 * @date 2021/4/2810:46
 */
@Slf4j
public class NettyServer {
    private static NettyServer instance = new NettyServer();
    private MyServerInitializer myChannelInitializer = new MyServerInitializer();
    public static NettyServer getInstance() {
        return instance;
    }
    public void startServer() throws InterruptedException {
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);    //用户处理客户端连接
        EventLoopGroup workerGroup = new NioEventLoopGroup();           //用于处理每一条连接的具体数据的读写
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();          //启动引导类
            bootstrap.group(bossGroup, workerGroup);                    //给引导类设置两大线程组
            bootstrap.channel(NioServerSocketChannel.class);            //设置IO模型,非阻塞模式
            bootstrap.option(ChannelOption.TCP_NODELAY, true);     //设置低延迟
            bootstrap.option(ChannelOption.SO_KEEPALIVE, true);    //开启SOCKET默认的心跳机制
            bootstrap.childHandler(myChannelInitializer);               //设置通道初始化器
            ChannelFuture future = bootstrap.bind(8888).sync();  //绑定端口,调用sync阻塞直至绑定完成
            future.channel().closeFuture().sync();                      //阻塞等到直到服务器Channel关闭
        } finally {
            bossGroup.shutdownGracefully();                             //优雅的关闭相关的线程资源
            workerGroup.shutdownGracefully();                           //优雅的关闭相关的线程资源
        }
    }

}
